package com.syncomponents.xml.convert;

import java.util.Locale;

import org.apache.commons.codec.binary.Base64;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;


/**
 * 支持文件流传传输，base64转码后传输
 * 
 * @author sunkey
 * @date Mar 26, 2014
 */
public class BytesConverter implements Converter {
    
    public BytesConverter() {
    }

    public BytesConverter(Locale locale) {
        super();
    }

    @SuppressWarnings("rawtypes")
    public boolean canConvert(Class clazz) {
        return byte[].class.isAssignableFrom(clazz);
    }

    public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
        byte[] byteValues = (byte[]) value;
        String result = Base64.encodeBase64String(byteValues);
        writer.setValue(result);
    }

    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        byte[] result = Base64.decodeBase64(reader.getValue());
        return result;
    }
}